package com.mano233.server.config.security;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.mano233.server.service.serviceImpl.FastDfsServiceImpl;
import com.mano233.server.tool.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @author mano233
 */
@Component
public class JwtAuthTokenFilter extends OncePerRequestFilter {
    private final UserCustomDetailServiceImpl userDetailsService;
    private static Logger logger = LoggerFactory.getLogger(FastDfsServiceImpl.class);

    @Autowired
    public JwtAuthTokenFilter(UserCustomDetailServiceImpl userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 提取请求头中的Authorization字段
        String authHeader = httpServletRequest.getHeader("Authorization");
        if (authHeader == null) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        if ("".equals(authHeader.trim())) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        // 如果token能够解析，则token有效
        DecodedJWT jwt = JwtUtil.verifyToken(authHeader);
        if (jwt != null) {
            // 构造userDetails
            UserCustomDetails userDetails = new UserCustomDetails();
            Set<GrantedAuthority> authoritiesSet = new HashSet<>(5);
            // 设置角色
            GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");
            authoritiesSet.add(authority);
            userDetails.setAuthorities(authoritiesSet);
            userDetails.setUserId(jwt.getClaim("userId").asInt());
            userDetails.setToken(authHeader);
            // 构造Authentication对象，交给Security框架
            UsernamePasswordAuthenticationToken authToken =
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authToken);
            // 继续处理其他过滤器
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }

    }
}
